<script>
import { getGraghByName } from './stSvgStruct'

export default {
  name: 'NeuSvg',
  props: {
    width: {
      type: String
    },
    height: {
      type: String
    },
    viewBox: {
      type: String
    },
    name: {
      type: String
    },
    color: {
      type: String
    }
  },
  data() {
    return {
      svgColor: this.color ? this.color : '#000000'
    }
  },
  watch: {
    color(val) {
      this.svgColor = val
    }
  },
  methods: {
    getAttrsObjByStr(str) {
      if (!str) {
        return ''
      }
      const obj = {}
      // eslint-disable-next-line
      let arr = str.match(/([\w-]+)\=\"(.*?)\"/g);
      for (const kv of arr) {
        var arrKv = kv.split('=')
        obj[arrKv[0]] = arrKv[1].split('"').join('')
      }
      return obj
    }
  },
  render: function(createElement) {
    if (!this.name) {
      return ''
    }
    const gragh = getGraghByName(this.name, this.svgColor, this.viewBox)
    const root = createElement(
      'svg',
      {
        attrs: {
          width: this.width ? this.width : '32px',
          height: this.height ? this.height : '32px',
          // 画布大小，默认不传，当下载的图片不是22*22时传入
          viewBox: this.viewBox ? this.viewBox : '0 0 32 32',
          version: '1.1',
          xmlns: 'http://www.w3.org/2000/svg'
        }
      },
    )
    root.children = []

    function renderChildren(lVNode, gragh) {
      if (gragh.children) {
        lVNode.children = []
        for (const nextGragh of gragh.children) {
          if (!nextGragh.label) {
            console.error('secondGragh label没有指定')
          }
          const nextLVNode = createElement(
            nextGragh.label,
            {
              attrs: this.getAttrsObjByStr(nextGragh.attrs)
            },
          )
          if (nextGragh.children) {
            renderChildren.call(this, nextLVNode, nextGragh)
          }
          lVNode.children.push(nextLVNode)
        }
      }
    }

    for (const secondGragh of gragh) {
      if (!secondGragh.label) {
        console.error('secondGragh label没有指定')
      }
      const secondLVNode = createElement(
        secondGragh.label,
        {
          attrs: this.getAttrsObjByStr(secondGragh.attrs)
        },
      )
      renderChildren.call(this, secondLVNode, secondGragh)
      root.children.push(secondLVNode)
    }
    return root
  }
}
</script>
